//
//  NewFeatureController.swift
//  MicroBlog
//
//  Created by QT on 15/7/31.
//  Copyright © 2015年 綦敦涛. All rights reserved.
//

import UIKit

private let reuseIdentifier = "Cell"
private let cellCount = 4
class NewFeatureController: UICollectionViewController {

    private let layout = HMFlowLayout()
    // 没有带override ,因为collectionView指定的构造函数是带layout的
    init(){
        super.init(collectionViewLayout: layout)
    }
    required init?(coder aDecoder: NSCoder) {
//        fatalError("init(coder:) has not been implemented")
        super.init(coder: aDecoder)
        
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()

        
        // Uncomment the following line to preserve selection between presentations
        // self.clearsSelectionOnViewWillAppear = false

        // Register cell classes
        self.collectionView!.registerClass(HMNewFeatureCell.self, forCellWithReuseIdentifier: reuseIdentifier)

        // Do any additional setup after loading the view.
    }



       // MARK: UICollectionViewDataSource

    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of items
        return cellCount
    }

    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! HMNewFeatureCell
    
        // Configure the cell
        cell.imgIndex = indexPath.item
    
        return cell
    }
    
    override func collectionView(collectionView: UICollectionView, didEndDisplayingCell cell: UICollectionViewCell, forItemAtIndexPath indexPath: NSIndexPath) {
        // 获取正要显示的cell索引
        var visibleItems = collectionView.indexPathsForVisibleItems().last
        if visibleItems?.item == cellCount - 1{
            // 获取正要显示的cell
            var cell = collectionView.cellForItemAtIndexPath(visibleItems!) as! HMNewFeatureCell
            // 设置cell动画
            cell.btnStartAni()
        }
 }

}


// 自定义cell
class HMNewFeatureCell: UICollectionViewCell {
    
    //  根据索引，设置cell内容
    private var imgIndex = 0{
        didSet{
            img.image = UIImage(named: "new_feature_\(imgIndex+1)")
//            btnStartAni()
        }
    }
    
    // 设置按钮动画
    func btnStartAni(){
        startBtn.hidden = false
        startBtn.userInteractionEnabled = false
        startBtn.transform = CGAffineTransformMakeScale(0, 0)
        UIView.animateWithDuration(1, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 7, options: UIViewAnimationOptions.CurveEaseIn, animations: { () -> Void in
            // 按钮变回初始大小
            self.startBtn.transform = CGAffineTransformIdentity
            self.startBtn.alpha = 1
            }) { (_) -> Void in
                self.startBtn.userInteractionEnabled = true
                // TODO: 动画执行完成,显示欢迎界面
        }
        
    }
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        // 隐藏“开始体验按钮”
        startBtn.hidden = true
        startBtn.alpha  = 0
        // 添加子空间
        contentView.addSubview(img)
        contentView.addSubview(startBtn)
        
        
        // 设置img的约束
        img.ff_Fill(contentView)
//        img.translatesAutoresizingMaskIntoConstraints = false
//        contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[subview]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["subview": img]))
//        contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[subview]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["subview": img]))
        
        // 设置startBtn约束
        startBtn.ff_AlignInner(type: ff_AlignType.BottomCenter, referView: contentView, size: nil, offset: CGPointMake(0, -200))
//        startBtn.translatesAutoresizingMaskIntoConstraints = false
//        contentView.addConstraint(NSLayoutConstraint(item: startBtn, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: contentView, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0))
//        
//        contentView.addConstraint(NSLayoutConstraint(item: startBtn, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: contentView, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: -200))
        
        
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    // 懒加载
    private lazy var img = UIImageView()
    private lazy var startBtn:UIButton = {
       let btn = UIButton()
        btn.setBackgroundImage(UIImage(named: "new_feature_finish_button"), forState: UIControlState.Normal)
        btn.setBackgroundImage(UIImage(named: "new_feature_finish_button_Highlighted"), forState: UIControlState.Highlighted)
        btn.setTitle("开始体验", forState: UIControlState.Normal)
        
        // 添加按钮事件
        btn.addTarget(self, action: "startExp", forControlEvents: UIControlEvents.TouchUpInside)
        return btn
    }()
    
    // 开始体验
    
    func startExp(){
       // 开始体验
       NSNotificationCenter.defaultCenter().postNotificationName(ViewControllerNotification, object: true)
    }
}




// 自定义layout
private class HMFlowLayout: UICollectionViewFlowLayout {
    // collectionView 显示内容或者失效前会调用此方法，更新布局
    private override func prepareLayout() {
        minimumInteritemSpacing = 0
   
        minimumLineSpacing   = 0
        scrollDirection = UICollectionViewScrollDirection.Horizontal
        itemSize = (collectionView?.bounds.size)!
        
        collectionView?.showsHorizontalScrollIndicator = false
        collectionView?.pagingEnabled = true
        collectionView?.bounces = false
        
    }
}
